<template>
  <div>
    <div class="gameEntry_shadow">
      <div class="table_title">
        已报名 {{ tableData.length }} 人
      </div>

      <!-- 运动员表格 -->
      <el-table ref="playerTable" v-loading="tableLoading" class="error_mark_wrap gl_mb_20 entry_table" :data="tableData" stripe size="mini">
        <el-table-column type="index" label="序号" width="50" align="center" />
        <el-table-column prop="name" label="运动员" width="160">
          <template slot-scope="scope">
            <span :class="scope.row._mark ? 'mark' : ''">{{ scope.row.name }}</span>
            <span v-if="scope.row.sourceRegister.gender && scope.row.sourceRegister.gender.name" :class="scope.row._mark ? 'mark' : ''">({{ scope.row.sourceRegister.gender.name }})</span>
          </template>
        </el-table-column>
        <template v-if="gameInfo.isFinal">
          <el-table-column prop="subCompetition" label="参报赛区" width="120">
            <template slot-scope="scope">
              <span>{{ scope.row.subCompetition ? scope.row.subCompetition.name : '' }}</span>
            </template>
          </el-table-column>
        </template>
        <el-table-column prop="entrys" label="个人项目">
          <template slot-scope="scope">
            <template v-for="(item, index) in scope.row.entrys">
              <el-tooltip :key="index" :content="item.event.eventGroup.category.name + item.event.eventGroup.name + item.event.name + `${item.teamNo ? item.teamNo + '组' : '' }`" placement="left" effect="light">
                <div
                  v-if="!item.teamEntry"
                  :key="index"
                  class="event_border gl_ellipsis"
                  :class="scope.row._mark && item.teamEntry && item.teamEntry.id === scope.row._markId ? 'mark' : ''"
                >
                  <span>{{ item.event.eventGroup.category.name }} </span>
                  <span>{{ item.event.eventGroup.name }}</span>
                  <span>{{ item.event.name }}</span>
                  <span v-if="item.teamNo">{{ item.teamNo }}组</span>
                </div>
              </el-tooltip>
            </template>
          </template>
        </el-table-column>
        <el-table-column prop="entrys" label="团体项目">
          <template slot-scope="{row}">
            <template v-for="(item, index) in row.entrys">
              <el-tooltip :key="index" :content="item.event.eventGroup.category.name + item.event.eventGroup.name + item.event.name+ `${item.weightClass ? ' (' + item.weightClass.name + ') ' : '' }` + `${item.teamNo ? item.teamNo + '组' : '' }`" placement="left" effect="light">
                <div
                  v-if="item.teamEntry"
                  :key="index"
                  class="event_border gl_ellipsis"
                  :class="row._mark && item.teamEntry && item.teamEntry.id === row._markId ? 'mark' : ''"
                >
                  <span>{{ item.event.eventGroup.category.name }} </span>
                  <span>{{ item.event.eventGroup.name }}</span>
                  <span>{{ item.event.name }}</span>
                  <span v-if="item.weightClass && item.weightClass.name"> ({{ item.weightClass.name }}) </span>
                  <span v-if="item.teamNo">{{ item.teamNo }}组</span>

                </div>
              </el-tooltip>
            </template>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="150">
          <template slot-scope="scope">
            <el-button class="gl_mr_10" size="mini" type="text" @click="clickTableEdit(scope.row)">编辑</el-button>
            <el-button size="mini" type="text" @click="clickTableDel(scope.row)">删除</el-button>
            <el-button type="text" @click="dataUpload(scope.row)">资料上传</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 按钮 -->
    <el-row>
      <el-col :span="24" align="center" class="control_row">
        <el-button type="default" @click="clickPrevStep()">上一步</el-button>
        <el-button type="primary" :loading="confirmEntriesLoading" :disabled="!tableData.length" @click="clickSubmit()">下一步</el-button>
      </el-col>
    </el-row>
    <UploadData ref="uploadData" />
  </div>
</template>

<script>
import { CopyData } from '@/lib';
import UploadData from './uploadData';
import {
  api_GET_EventsManagementEntryByPerson, // 12-查询报项（按个人汇总报项）
  // api_DELETE_EventsManagementEntryComRegister, // 5-1-删除报名,同时删除全部报项，同时删除CompetitionRegister相关联内容  (旧接口，报名拆分需求之前使用)
  api_DELETE_EventsManagementEntryCompetitionRegisters, // 删除报项人员   (新接口，报名拆分需求之后使用)
  api_POST_EventsManagementEntryConfirmEntries // 6-确认报项，只用于非收费赛事，将报项变更为待审核
} from '@/extend/api/gameswaggerApi/app';

import {
  Api_GET_EventsManagementEntryByPersonQO // 11-查询报项（返回报项汇总）
} from '@/lib/form/game/swaggerForm';

export default {
  components: {
    UploadData
  },
  props: {
    currentUserType: {
      type: String,
      default: ''
    },
    propData: {
      type: Object,
      default() {
        return {};
      }
    },
    gameInfo: {
      type: Object,
      default() {
        return {};
      }
    },
    requiredIdData: {
      type: Object,
      default () {
        return {};
      }
    }
  },
  data () {
    return {
      qo: new Api_GET_EventsManagementEntryByPersonQO(),
      total: 0,
      tableData: [],
      tableLoading: false,
      spanArr: [], // 表格合并
      tableKey: null,
      confirmEntriesLoading: false,
      removedAthleteId: '' // 被删除报项的运动员ID，用于传给父组件，如果父组件当前选中的运动员与此ID一致，则重新获取项目
    };
  },
  created() {
    delete this.qo.SkipCount;
    delete this.qo.Page;
    delete this.qo.MaxResultCount;
  },
  methods: {
    // 点击执行上一步操作
    clickPrevStep () {
      this.$emit('onPrevStep');
    },
    // 获取页面信息
    getPageList() {
      CopyData(this.propData, this.qo);
      this.tableLoading = true;
      api_GET_EventsManagementEntryByPerson(this.qo)
        .then(
          res => {
            console.log(res);
            this.tableData = res.items;
            this.total = res.totalCount;
            this.tableLoading = false;
            this.$emit('onMatchAthleteEntryFromByPerson', res.items);
          }
        )
        .catch(
          error => {
            this.tableLoading = false;
            this.$message({
              message: `报项列表获取失败！ ${error.error.message}`,
              type: 'error',
              showClose: true
            });
          }
        );
    },
    // 点击表格编辑row
    clickTableEdit (item) {
      if (this.currentUserType === 'Delegation') {
        this.$emit('onDelegationContinue', item.sourceRegister);
      }
      if (this.currentUserType === 'Personal') {
        this.$emit('onPersonalContinue');
      }
    },
    // 资料上传
    dataUpload(row) {
      this.$refs.uploadData.open(row.id);
    },
    // 点击表格删除row
    clickTableDel (row) {

      this.$confirm(this.$route.query.code==='ApproveFailed'&&this.tableData.length===1?'人员全部删除后，已缴费记录将被清空且不可恢复，是否继续删除？':'您确定要删除该报名吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.removedAthleteId = row.sourceRegister.id;
          const _vo = {
            CompetitionRegisterIds: row.id,
            DelegationId: this.requiredIdData.delegationId,
            CompetitionId: this.gameInfo.id
          };
          if (!this.requiredIdData.delegationId) {
            // 个人报项删除时不可传delegationId 所以当delegationId没有时删除delegationId
            delete _vo.DelegationId;
          }
          this.removeEntry(_vo);
          // this.removeEntry({ comRegisterIds: row.id }); // (旧接口)
        });
    },
    // 移除报名API
    removeEntry (vo) {
      // api_DELETE_EventsManagementEntryComRegister(vo) // (旧接口)
      api_DELETE_EventsManagementEntryCompetitionRegisters(vo)
        .then(res => {
          this.$message({
            message: `删除报项成功！`,
            type: 'success',
            showClose: true
          });
          this.getPageList();
          this.$emit('onRemovedAthleteForCheckEntry', this.removedAthleteId);
        })
        .catch(
          error => {
            this.$message({
              message: `删除报项失败！ ${error.error.message}`,
              type: 'error',
              showClose: true
            });
          }
        );
    },
    // 确认报名
    clickSubmit () {
      const _vo = {
        competitionId: this.gameInfo.id,
        delegationId: this.requiredIdData.delegationId,
        registerId: this.requiredIdData.registerId
      };

      if (this.currentUserType === 'Personal') {
        _vo.delegationId = null;
      }
      this.confirmEntryForGame(_vo);
    },
    confirmEntryForGame (vo) {
      this.confirmEntriesLoading = true;
      this.removeTableDataMarkForError();
      api_POST_EventsManagementEntryConfirmEntries(vo)
        .then(
          res => {
            this.confirmEntriesLoading = false;
            this.$emit('onConfirmEntry');
          }
        )
        .catch(
          error => {
            this.confirmEntriesLoading = false;
            console.log('error: ', error);
            if (error.error.code === 'SubCompetitionNotNull') {
              // 参报赛区为空，标记出所有参报赛区为空的表格条目
              this.markTableDataForSubCompetitionNotNull();
            } else {
              const _teamEntryId = error.error.details || '';
              this.markTableDataForError(_teamEntryId);
            }
            this.$message({
              message: `${error.error.message}`,
              type: 'error',
              showClose: true
            });
          }
        );
    },
    // 移除表格中被标记错误的数据
    removeTableDataMarkForError () {
      for (let i = 0; i < this.tableData.length; i++) {
        const item = this.tableData[i];
        if (item._mark) {
          item._mark = false;
          item._markId = '';
          this.tableData.splice(i, 1, item);
        }
      }
    },
    markTableDataForSubCompetitionNotNull () {
      for (let i = 0; i < this.tableData.length; i++) {
        const item = this.tableData[i];
        if (!item.subCompetition) {
          item._mark = true;
          this.tableData.splice(i, 1, item);
        }
      }
    },
    // 标记表格中的报项错误数据
    markTableDataForError (id) {
      if (!id) return;
      for (let i = 0; i < this.tableData.length; i++) {
        const item = this.tableData[i];
        const _entrys = item.entrys || [];
        for (let j = 0; j < _entrys.length; j++) {
          const jtem = _entrys[j];
          if (jtem.teamEntry && jtem.teamEntry.id === id) {
            item._mark = true;
            item._markId = jtem.teamEntry.id;
            this.tableData.splice(i, 1, item);
          }
        }
      }
    }
  }
};
</script>

<style scoped>
.gameEntry_shadow {
  padding: 20px 30px;
}

.table_title {
  padding-bottom: 10px;
  color: #333;
  font-weight: bold;
  font-size: 14px;
}
.event_border {
  padding: 2px 0;
  border-bottom: 1px solid #dfe6ec;
}
.event_border:last-child{
  border-bottom: none;
}

.error_mark_wrap .mark {
  color: red;
}
</style>

<style>
.gameEntry_shadow .entry_table{
  min-height: auto;
}
.gameEntry_shadow .entry_table .el-table__body-wrapper{
  height: auto !important;
  min-height: 177px;
}
</style>
